﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;

namespace Mga
{
	[RequireComponent(typeof(LuaInjectionData))]
	public class LuaPanel : BaseView
	{
		public string FormLuaName;
		private LuaTable scriptEnv;
		private LuaEnv luaEnv;
		private Action luaStart;
		private Action luaUpdate;
		//private Action luaOnDestroy;
		//private Action<object> luaOnInit;
		//private Action<object> luaOnOpen;
		//private Action<object> luaOnClose;
		//private Action luaOnPause;
		//private Action luaOnResume;
		//private Action luaOnCover;
		//private Action luaOnReveal;
		//private Action<object> luaOnReFocus;
		//private Action<float, float> luaOnUpdate;
		//private Action<int, int> luaOnDepthChanged;
		void Awake()
		{
			luaEnv = XLuaComponent.LuaEnv;
			scriptEnv = luaEnv.NewTable();
			var c = GetComponent<LuaInjectionData>();
			c.Data.Set("__index", luaEnv.Global);
			scriptEnv.SetMetaTable(c.Data);

			scriptEnv.Set("self", this);

			if (!string.IsNullOrEmpty(FormLuaName))
			{
				luaEnv.DoString(XLuaComponent.ReadFile(FormLuaName), "LuaUguiForm", scriptEnv);
			}

			Action luaAwake = scriptEnv.Get<Action>("awake");
			scriptEnv.Get("start", out luaStart);
			scriptEnv.Get("update", out luaUpdate);
			//scriptEnv.Get("ondestroy", out luaOnDestroy);
			//scriptEnv.Get("onInit", out luaOnInit);
			//scriptEnv.Get("onOpen", out luaOnOpen);
			//scriptEnv.Get("onClose", out luaOnClose);
			//scriptEnv.Get("onPause", out luaOnPause);
			//scriptEnv.Get("onResume", out luaOnResume);
			//scriptEnv.Get("onCover", out luaOnCover);
			//scriptEnv.Get("onReveal", out luaOnReveal);
			//scriptEnv.Get("onRefocus", out luaOnReFocus);
			//scriptEnv.Get("onDepthChanged", out luaOnDepthChanged);

			if (luaAwake != null)
			{
				luaAwake();
			}
		}

		void Start()
		{
			if (luaStart != null)
				luaStart();
		}

		void Update()
		{
			if (luaUpdate != null)
				luaUpdate();
		}
	}
}